package org.sparkle.html.api;

import java.util.HashMap;
import java.util.Map;

import org.sparkle.html.impl.basic.Div;
import org.sparkle.web.session.MainManager;

public abstract class AbstractWidget extends Div{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3251993373960986996L;
	protected JScript script;
	protected Map<String,String> scriptAttributes;
	
	public AbstractWidget() {
		init();
	}
	
	@Override
	public void setId(String id) {
		super.setId(id);
		refreshScript();
	}
	
	protected void refreshScript(){
		String scriptBody="$(\"#"+getWidgetId()+"\")."+getScriptTag()+"({";
		for(String s: scriptAttributes.keySet()){
			scriptBody+=(s+":"+scriptAttributes.get(s));
			scriptBody+=",";
		}
		if(scriptBody.endsWith(",")){
			scriptBody=scriptBody.substring(0, scriptBody.length()-1);
		}
		scriptBody+="});";
		script.setScript(scriptBody);
		//AppManager.getAppState()
		MainManager.getAppSession().getAppState().addScript(script);
	}
	
	protected String getWidgetId(){
		return getId();
	}
	
	protected Map<String,String> getScriptAttribute(){
		return scriptAttributes;
	}
	
	public String getScriptTag(){
		return this.getClass().getName().replaceFirst(this.getClass().getPackage().getName()+".", "").toLowerCase();
	}
	
	protected void init(){
		script=new JScript();
		scriptAttributes=new HashMap<String, String>();
		//Html.addScript(script);
		refreshScript();
		//AppManager.getAppState()
		MainManager.getAppSession().getAppState().addScript(script);
	}
	
	@Override
	public String getTag() {
		return "div";
	}
}
